package com.vrv.vap.server.service.impl;

import com.vrv.vap.domain.LoginUser;
import com.vrv.vap.server.entity.Role;
import com.vrv.vap.server.entity.User;
import com.vrv.vap.server.service.RoleService;
import com.vrv.vap.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wh1107066
 * @date 2021/6/24 17:34
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.selectUserByName(username);
        if (user == null) {
            throw new RuntimeException("用户不存在!");
        }
        List<Role> list = roleService.selectRolesByUserId(user.getId());
        if (list == null || list.size() == 0) {
            throw new RuntimeException("未配置角色信息");
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList(list.size());
        for (Role role : list) {
            grantedAuthorities.add(new SimpleGrantedAuthority(role.getRoleName()));
        }
        return new LoginUser(user.getUsername(), user.getPassword(), grantedAuthorities);
    }
}
